package com.hanzhong.travel.controller;

import com.hanzhong.travel.entity.HanCultureActivity;
import com.hanzhong.travel.service.HanCultureActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 汉文化活动控制器
 */
@RestController
@RequestMapping("/api/activities")
public class HanCultureActivityController {

    @Autowired
    private HanCultureActivityService activityService;

    /**
     * 支持OPTIONS请求
     */
    @RequestMapping(method = RequestMethod.OPTIONS)
    public ResponseEntity<?> options() {
        return ResponseEntity.ok().build();
    }

    /**
     * 添加活动
     */
    @PostMapping
    public ResponseEntity<?> addActivity(@RequestBody HanCultureActivity activity) {
        System.out.println("收到添加活动请求: " + activity.getTitle());
        boolean success = activityService.addActivity(activity);
        if (success) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "活动添加成功");
            result.put("data", activity);
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body("活动添加失败");
        }
    }

    /**
     * 更新活动
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateActivity(@PathVariable Long id, @RequestBody HanCultureActivity activity) {
        System.out.println("收到更新活动请求: " + id);
        activity.setId(id);
        boolean success = activityService.updateActivity(activity);
        if (success) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "活动更新成功");
            result.put("data", activity);
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body("活动更新失败");
        }
    }

    /**
     * 删除活动
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteActivity(@PathVariable Long id) {
        System.out.println("收到删除活动请求: " + id);
        boolean success = activityService.deleteActivity(id);
        if (success) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "活动删除成功");
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body("活动删除失败");
        }
    }

    /**
     * 获取单个活动详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getActivityById(@PathVariable Long id) {
        System.out.println("收到获取活动详情请求: " + id);
        HanCultureActivity activity = activityService.getActivityById(id);
        if (activity != null) {
            return ResponseEntity.ok(activity);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 获取所有活动
     */
    @GetMapping
    public ResponseEntity<?> getAllActivities() {
        System.out.println("收到获取所有活动请求");
        List<HanCultureActivity> activities = activityService.getAllActivities();
        return ResponseEntity.ok(activities);
    }

    /**
     * 分页获取活动
     */
    @GetMapping("/page")
    public ResponseEntity<?> getActivitiesByPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        System.out.println("收到分页获取活动请求: page=" + page + ", size=" + size);
        Map<String, Object> result = activityService.getActivitiesByPage(page, size);
        return ResponseEntity.ok(result);
    }

    /**
     * 根据状态获取活动
     */
    @GetMapping("/status/{status}")
    public ResponseEntity<?> getActivitiesByStatus(@PathVariable Integer status) {
        System.out.println("收到按状态获取活动请求: status=" + status);
        List<HanCultureActivity> activities = activityService.getActivitiesByStatus(status);
        return ResponseEntity.ok(activities);
    }

    /**
     * 上传活动图片
     */
    @PostMapping("/upload")
    public ResponseEntity<?> uploadImage(@RequestParam("file") MultipartFile file) {
        System.out.println("收到上传图片请求");
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("请选择文件");
        }

        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 生成新文件名
            String newFileName = UUID.randomUUID().toString() + 
                    fileName.substring(fileName.lastIndexOf("."));
            
            // 确定文件存储路径
            String uploadDir = "uploads/activities/";
            Path uploadPath = Paths.get(uploadDir);
            
            // 如果目录不存在，创建目录
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 保存文件
            Path filePath = Paths.get(uploadDir + newFileName);
            Files.write(filePath, file.getBytes());
            
            // 返回文件访问路径
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "文件上传成功");
            result.put("url", "/uploads/activities/" + newFileName);
            
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("文件上传失败: " + e.getMessage());
        }
    }
} 